<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebXR 权限测试 - Vision Pro</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
        }

        h1 {
            text-align: center;
            font-size: 2.5em;
            margin-bottom: 30px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .test-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .test-card {
            background: rgba(255,255,255,0.1);
            border-radius: 15px;
            padding: 25px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            transition: transform 0.3s ease;
        }

        .test-card:hover {
            transform: translateY(-5px);
        }

        .test-card h3 {
            margin-bottom: 15px;
            color: #FFD700;
        }

        .permission-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .permission-item:last-child {
            border-bottom: none;
        }

        .status-badge {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-granted { background: #4CAF50; }
        .status-denied { background: #F44336; }
        .status-prompt { background: #FF9800; }
        .status-unknown { background: #9E9E9E; }

        .action-button {
            background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
            border: none;
            color: white;
            padding: 12px 24px;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 5px;
            font-size: 14px;
        }

        .action-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }

        .action-button:disabled {
            background: #666;
            cursor: not-allowed;
            transform: none;
        }

        .feature-test {
            background: rgba(255,255,255,0.05);
            border-radius: 10px;
            padding: 15px;
            margin: 10px 0;
        }

        .feature-test h4 {
            color: #87CEEB;
            margin-bottom: 10px;
        }

        .test-result {
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 12px;
            background: rgba(0,0,0,0.3);
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            max-height: 150px;
            overflow-y: auto;
        }

        .log-container {
            background: rgba(0,0,0,0.4);
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            max-height: 400px;
            overflow-y: auto;
        }

        .log-entry {
            margin: 5px 0;
            padding: 8px;
            border-radius: 5px;
            border-left: 4px solid;
        }

        .log-info { border-color: #2196F3; background: rgba(33, 150, 243, 0.1); }
        .log-success { border-color: #4CAF50; background: rgba(76, 175, 80, 0.1); }
        .log-warning { border-color: #FF9800; background: rgba(255, 152, 0, 0.1); }
        .log-error { border-color: #F44336; background: rgba(244, 67, 54, 0.1); }

        .device-info {
            background: rgba(255,255,255,0.08);
            border-radius: 10px;
            padding: 15px;
            margin: 15px 0;
        }

        .info-row {
            display: flex;
            justify-content: space-between;
            margin: 8px 0;
            font-size: 14px;
        }

        .info-label {
            font-weight: bold;
            color: #FFD700;
        }

        .progress-bar {
            width: 100%;
            height: 6px;
            background: rgba(255,255,255,0.2);
            border-radius: 3px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4CAF50, #8BC34A);
            transition: width 0.3s ease;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🥽 WebXR 权限测试中心</h1>
        
        <div class="test-grid">
            <!-- 设备信息卡片 -->
            <div class="test-card">
                <h3>📱 设备信息</h3>
                <div class="device-info">
                    <div class="info-row">
                        <span class="info-label">用户代理:</span>
                        <span id="user-agent-short">检测中...</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">设备类型:</span>
                        <span id="device-type">检测中...</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">平台:</span>
                        <span id="platform">检测中...</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">WebXR支持:</span>
                        <span id="webxr-support">检测中...</span>
                    </div>
                </div>
                <button class="action-button" onclick="refreshDeviceInfo()">刷新信息</button>
            </div>

            <!-- 基础权限卡片 -->
            <div class="test-card">
                <h3>🔐 基础权限</h3>
                <div id="basic-permissions">
                    <div class="permission-item">
                        <span>相机权限</span>
                        <span class="status-badge status-unknown" id="camera-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>麦克风权限</span>
                        <span class="status-badge status-unknown" id="microphone-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>设备方向</span>
                        <span class="status-badge status-unknown" id="orientation-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>设备运动</span>
                        <span class="status-badge status-unknown" id="motion-status">未知</span>
                    </div>
                </div>
                <button class="action-button" onclick="checkBasicPermissions()">检查权限</button>
                <button class="action-button" onclick="requestBasicPermissions()">申请权限</button>
            </div>

            <!-- WebXR功能卡片 -->
            <div class="test-card">
                <h3>🥽 WebXR 功能</h3>
                <div id="webxr-features">
                    <div class="permission-item">
                        <span>沉浸式VR</span>
                        <span class="status-badge status-unknown" id="immersive-vr-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>手部追踪</span>
                        <span class="status-badge status-unknown" id="hand-tracking-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>眼部追踪</span>
                        <span class="status-badge status-unknown" id="eye-tracking-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>平面检测</span>
                        <span class="status-badge status-unknown" id="plane-detection-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>锚点</span>
                        <span class="status-badge status-unknown" id="anchors-status">未知</span>
                    </div>
                </div>
                <button class="action-button" onclick="checkWebXRFeatures()">检查功能</button>
                <button class="action-button" onclick="testWebXRSession()">测试会话</button>
            </div>

            <!-- 高级功能卡片 -->
            <div class="test-card">
                <h3>⚡ 高级功能</h3>
                <div id="advanced-features">
                    <div class="permission-item">
                        <span>DOM覆盖</span>
                        <span class="status-badge status-unknown" id="dom-overlay-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>本地地板</span>
                        <span class="status-badge status-unknown" id="local-floor-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>有界地板</span>
                        <span class="status-badge status-unknown" id="bounded-floor-status">未知</span>
                    </div>
                    <div class="permission-item">
                        <span>无界空间</span>
                        <span class="status-badge status-unknown" id="unbounded-status">未知</span>
                    </div>
                </div>
                <button class="action-button" onclick="checkAdvancedFeatures()">检查功能</button>
            </div>
        </div>

        <!-- 测试进度 -->
        <div class="test-card">
            <h3>📊 测试进度</h3>
            <div class="progress-bar">
                <div class="progress-fill" id="test-progress" style="width: 0%"></div>
            </div>
            <div style="text-align: center; margin-top: 10px;">
                <span id="progress-text">0% 完成</span>
            </div>
            <div style="text-align: center; margin-top: 15px;">
                <button class="action-button" onclick="runAllTests()">运行所有测试</button>
                <button class="action-button" onclick="clearAllResults()">清空结果</button>
            </div>
        </div>

        <!-- 详细测试结果 -->
        <div class="test-card">
            <h3>🔍 详细测试结果</h3>
            <div id="detailed-results">
                <div class="feature-test">
                    <h4>WebXR 会话测试</h4>
                    <div class="test-result" id="session-test-result">等待测试...</div>
                    <button class="action-button" onclick="testSessionCreation()">测试会话创建</button>
                </div>
                
                <div class="feature-test">
                    <h4>输入源检测</h4>
                    <div class="test-result" id="input-source-result">等待测试...</div>
                    <button class="action-button" onclick="testInputSources()">检测输入源</button>
                </div>
                
                <div class="feature-test">
                    <h4>参考空间测试</h4>
                    <div class="test-result" id="reference-space-result">等待测试...</div>
                    <button class="action-button" onclick="testReferenceSpaces()">测试参考空间</button>
                </div>
            </div>
        </div>

        <!-- 日志区域 -->
        <div class="test-card">
            <h3>📝 测试日志</h3>
            <button class="action-button" onclick="clearLog()">清空日志</button>
            <button class="action-button" onclick="exportLog()">导出日志</button>
            <div id="log-container" class="log-container"></div>
        </div>
    </div>

    <script>
        // 全局变量
        let testProgress = 0;
        let totalTests = 0;
        let completedTests = 0;

        // 日志系统
        function log(message, type = 'info') {
            const logContainer = document.getElementById('log-container');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${type}`;
            logEntry.innerHTML = `<strong>[${timestamp}]</strong> ${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
            console.log(`[${type.toUpperCase()}] ${message}`);
        }

        function clearLog() {
            document.getElementById('log-container').innerHTML = '';
            log('日志已清空', 'info');
        }

        function exportLog() {
            const logContainer = document.getElementById('log-container');
            const logText = logContainer.innerText;
            const blob = new Blob([logText], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `webxr-test-log-${new Date().toISOString().slice(0,19).replace(/:/g,'-')}.txt`;
            a.click();
            URL.revokeObjectURL(url);
            log('日志已导出', 'success');
        }

        // 更新状态
        function updateStatus(elementId, status, text = null) {
            const element = document.getElementById(elementId);
            if (element) {
                element.className = `status-badge status-${status}`;
                if (text) element.textContent = text;
                else {
                    switch (status) {
                        case 'granted': element.textContent = '已授权'; break;
                        case 'denied': element.textContent = '已拒绝'; break;
                        case 'prompt': element.textContent = '需申请'; break;
                        case 'unknown': element.textContent = '未知'; break;
                        default: element.textContent = status;
                    }
                }
            }
        }

        // 更新进度
        function updateProgress() {
            const percentage = totalTests > 0 ? Math.round((completedTests / totalTests) * 100) : 0;
            document.getElementById('test-progress').style.width = `${percentage}%`;
            document.getElementById('progress-text').textContent = `${percentage}% 完成 (${completedTests}/${totalTests})`;
        }

        // 刷新设备信息
        function refreshDeviceInfo() {
            log('刷新设备信息...', 'info');
            
            const userAgent = navigator.userAgent;
            document.getElementById('user-agent-short').textContent = userAgent.length > 30 ? 
                userAgent.substring(0, 30) + '...' : userAgent;
            
            document.getElementById('platform').textContent = navigator.platform || '未知';
            
            // 检测设备类型
            const deviceType = detectDeviceType();
            document.getElementById('device-type').textContent = deviceType;
            
            // 检测WebXR支持
            const webxrSupport = 'xr' in navigator ? '✅ 支持' : '❌ 不支持';
            document.getElementById('webxr-support').textContent = webxrSupport;
            
            log(`设备信息已更新: ${deviceType}`, 'success');
        }

        // 检测设备类型
        function detectDeviceType() {
            const userAgent = navigator.userAgent.toLowerCase();
            
            if (userAgent.includes('vision')) {
                return 'Apple Vision Pro';
            } else if (userAgent.includes('quest')) {
                return 'Meta Quest';
            } else if (userAgent.includes('pico')) {
                return 'Pico VR';
            } else if (userAgent.includes('vive')) {
                return 'HTC Vive';
            } else if (userAgent.includes('safari')) {
                return 'Safari (可能支持WebXR)';
            } else {
                return '未知设备';
            }
        }

        // 检查基础权限
        async function checkBasicPermissions() {
            log('检查基础权限...', 'info');
            totalTests += 4;
            
            // 检查相机权限
            try {
                const cameraPermission = await navigator.permissions.query({ name: 'camera' });
                updateStatus('camera-status', cameraPermission.state);
                log(`相机权限: ${cameraPermission.state}`, 'info');
                completedTests++;
            } catch (error) {
                updateStatus('camera-status', 'unknown', '不支持');
                log(`相机权限检查失败: ${error.message}`, 'warning');
                completedTests++;
            }
            
            // 检查麦克风权限
            try {
                const micPermission = await navigator.permissions.query({ name: 'microphone' });
                updateStatus('microphone-status', micPermission.state);
                log(`麦克风权限: ${micPermission.state}`, 'info');
                completedTests++;
            } catch (error) {
                updateStatus('microphone-status', 'unknown', '不支持');
                log(`麦克风权限检查失败: ${error.message}`, 'warning');
                completedTests++;
            }
            
            // 检查设备方向
            if ('DeviceOrientationEvent' in window) {
                updateStatus('orientation-status', 'granted', '支持');
                log('设备方向: 支持', 'success');
            } else {
                updateStatus('orientation-status', 'denied', '不支持');
                log('设备方向: 不支持', 'warning');
            }
            completedTests++;
            
            // 检查设备运动
            if ('DeviceMotionEvent' in window) {
                updateStatus('motion-status', 'granted', '支持');
                log('设备运动: 支持', 'success');
            } else {
                updateStatus('motion-status', 'denied', '不支持');
                log('设备运动: 不支持', 'warning');
            }
            completedTests++;
            
            updateProgress();
        }

        // 申请基础权限
        async function requestBasicPermissions() {
            log('申请基础权限...', 'info');
            
            // 申请相机和麦克风权限
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ 
                    video: true, 
                    audio: true 
                });
                stream.getTracks().forEach(track => track.stop());
                updateStatus('camera-status', 'granted');
                updateStatus('microphone-status', 'granted');
                log('相机和麦克风权限申请成功', 'success');
            } catch (error) {
                log(`媒体权限申请失败: ${error.message}`, 'error');
            }
            
            // 申请设备方向权限 (iOS 13+)
            if (typeof DeviceOrientationEvent.requestPermission === 'function') {
                try {
                    const permission = await DeviceOrientationEvent.requestPermission();
                    updateStatus('orientation-status', permission === 'granted' ? 'granted' : 'denied');
                    log(`设备方向权限: ${permission}`, permission === 'granted' ? 'success' : 'warning');
                } catch (error) {
                    log(`设备方向权限申请失败: ${error.message}`, 'error');
                }
            }
            
            // 申请设备运动权限 (iOS 13+)
            if (typeof DeviceMotionEvent.requestPermission === 'function') {
                try {
                    const permission = await DeviceMotionEvent.requestPermission();
                    updateStatus('motion-status', permission === 'granted' ? 'granted' : 'denied');
                    log(`设备运动权限: ${permission}`, permission === 'granted' ? 'success' : 'warning');
                } catch (error) {
                    log(`设备运动权限申请失败: ${error.message}`, 'error');
                }
            }
        }

        // 检查WebXR功能
        async function checkWebXRFeatures() {
            if (!('xr' in navigator)) {
                log('WebXR 不支持，跳过功能检查', 'error');
                return;
            }
            
            log('检查WebXR功能...', 'info');
            totalTests += 5;
            
            const features = [
                { name: 'immersive-vr', id: 'immersive-vr-status' },
                { name: 'hand-tracking', id: 'hand-tracking-status' },
                { name: 'eye-tracking', id: 'eye-tracking-status' },
                { name: 'plane-detection', id: 'plane-detection-status' },
                { name: 'anchors', id: 'anchors-status' }
            ];
            
            for (const feature of features) {
                try {
                    if (feature.name === 'immersive-vr') {
                        const supported = await navigator.xr.isSessionSupported('immersive-vr');
                        updateStatus(feature.id, supported ? 'granted' : 'denied', supported ? '支持' : '不支持');
                        log(`${feature.name}: ${supported ? '支持' : '不支持'}`, supported ? 'success' : 'warning');
                    } else {
                        // 对于其他功能，尝试创建会话来测试
                        try {
                            const session = await navigator.xr.requestSession('immersive-vr', {
                                optionalFeatures: [feature.name]
                            });
                            const supported = session.enabledFeatures && session.enabledFeatures.includes(feature.name);
                            updateStatus(feature.id, supported ? 'granted' : 'denied', supported ? '支持' : '不支持');
                            log(`${feature.name}: ${supported ? '支持' : '不支持'}`, supported ? 'success' : 'warning');
                            session.end();
                        } catch (error) {
                            updateStatus(feature.id, 'denied', '不支持');
                            log(`${feature.name}: 不支持 (${error.message})`, 'warning');
                        }
                    }
                } catch (error) {
                    updateStatus(feature.id, 'unknown', '检测失败');
                    log(`${feature.name} 检测失败: ${error.message}`, 'error');
                }
                completedTests++;
                updateProgress();
            }
        }

        // 检查高级功能
        async function checkAdvancedFeatures() {
            if (!('xr' in navigator)) {
                log('WebXR 不支持，跳过高级功能检查', 'error');
                return;
            }
            
            log('检查高级功能...', 'info');
            totalTests += 4;
            
            const features = [
                { name: 'dom-overlay', id: 'dom-overlay-status' },
                { name: 'local-floor', id: 'local-floor-status' },
                { name: 'bounded-floor', id: 'bounded-floor-status' },
                { name: 'unbounded', id: 'unbounded-status' }
            ];
            
            for (const feature of features) {
                try {
                    const sessionInit = feature.name === 'dom-overlay' ? 
                        { optionalFeatures: [feature.name], domOverlay: { root: document.body } } :
                        { optionalFeatures: [feature.name] };
                    
                    const session = await navigator.xr.requestSession('immersive-vr', sessionInit);
                    const supported = session.enabledFeatures && session.enabledFeatures.includes(feature.name);
                    updateStatus(feature.id, supported ? 'granted' : 'denied', supported ? '支持' : '不支持');
                    log(`${feature.name}: ${supported ? '支持' : '不支持'}`, supported ? 'success' : 'warning');
                    session.end();
                } catch (error) {
                    updateStatus(feature.id, 'denied', '不支持');
                    log(`${feature.name}: 不支持 (${error.message})`, 'warning');
                }
                completedTests++;
                updateProgress();
            }
        }

        // 测试WebXR会话
        async function testWebXRSession() {
            if (!('xr' in navigator)) {
                log('WebXR 不支持，无法测试会话', 'error');
                return;
            }
            
            log('测试WebXR会话创建...', 'info');
            
            try {
                const session = await navigator.xr.requestSession('immersive-vr', {
                    requiredFeatures: ['local-floor'],
                    optionalFeatures: ['hand-tracking', 'dom-overlay'],
                    domOverlay: { root: document.body }
                });
                
                log('WebXR会话创建成功', 'success');
                log(`启用的功能: ${session.enabledFeatures ? session.enabledFeatures.join(', ') : '无'}`, 'info');
                
                // 立即结束会话
                session.end();
                log('WebXR会话已结束', 'info');
                
            } catch (error) {
                log(`WebXR会话创建失败: ${error.message}`, 'error');
            }
        }

        // 测试会话创建
        async function testSessionCreation() {
            const resultElement = document.getElementById('session-test-result');
            resultElement.textContent = '测试中...';
            
            if (!('xr' in navigator)) {
                resultElement.textContent = '❌ WebXR 不支持';
                return;
            }
            
            try {
                const sessionModes = ['immersive-vr', 'immersive-ar', 'inline'];
                const results = [];
                
                for (const mode of sessionModes) {
                    try {
                        const supported = await navigator.xr.isSessionSupported(mode);
                        results.push(`${mode}: ${supported ? '✅' : '❌'}`);
                    } catch (error) {
                        results.push(`${mode}: ❌ (${error.message})`);
                    }
                }
                
                resultElement.innerHTML = results.join('<br>');
                log('会话模式测试完成', 'success');
                
            } catch (error) {
                resultElement.textContent = `❌ 测试失败: ${error.message}`;
                log(`会话测试失败: ${error.message}`, 'error');
            }
        }

        // 测试输入源
        async function testInputSources() {
            const resultElement = document.getElementById('input-source-result');
            resultElement.textContent = '测试中...';
            
            if (!('xr' in navigator)) {
                resultElement.textContent = '❌ WebXR 不支持';
                return;
            }
            
            try {
                const session = await navigator.xr.requestSession('immersive-vr', {
                    optionalFeatures: ['hand-tracking']
                });
                
                const inputSources = session.inputSources;
                const results = [`输入源数量: ${inputSources.length}`];
                
                inputSources.forEach((source, index) => {
                    results.push(`输入源 ${index + 1}:`);
                    results.push(`  - 类型: ${source.handedness || '未知'}`);
                    results.push(`  - 手部追踪: ${source.hand ? '✅' : '❌'}`);
                    results.push(`  - 游戏手柄: ${source.gamepad ? '✅' : '❌'}`);
                });
                
                resultElement.innerHTML = results.join('<br>');
                session.end();
                log('输入源测试完成', 'success');
                
            } catch (error) {
                resultElement.textContent = `❌ 测试失败: ${error.message}`;
                log(`输入源测试失败: ${error.message}`, 'error');
            }
        }

        // 测试参考空间
        async function testReferenceSpaces() {
            const resultElement = document.getElementById('reference-space-result');
            resultElement.textContent = '测试中...';
            
            if (!('xr' in navigator)) {
                resultElement.textContent = '❌ WebXR 不支持';
                return;
            }
            
            try {
                const session = await navigator.xr.requestSession('immersive-vr');
                
                const spaceTypes = ['viewer', 'local', 'local-floor', 'bounded-floor', 'unbounded'];
                const results = [];
                
                for (const spaceType of spaceTypes) {
                    try {
                        const referenceSpace = await session.requestReferenceSpace(spaceType);
                        results.push(`${spaceType}: ✅`);
                    } catch (error) {
                        results.push(`${spaceType}: ❌`);
                    }
                }
                
                resultElement.innerHTML = results.join('<br>');
                session.end();
                log('参考空间测试完成', 'success');
                
            } catch (error) {
                resultElement.textContent = `❌ 测试失败: ${error.message}`;
                log(`参考空间测试失败: ${error.message}`, 'error');
            }
        }

        // 运行所有测试
        async function runAllTests() {
            log('开始运行所有测试...', 'info');
            clearAllResults();
            
            refreshDeviceInfo();
            await checkBasicPermissions();
            await checkWebXRFeatures();
            await checkAdvancedFeatures();
            await testSessionCreation();
            await testInputSources();
            await testReferenceSpaces();
            
            log('所有测试完成', 'success');
        }

        // 清空所有结果
        function clearAllResults() {
            totalTests = 0;
            completedTests = 0;
            updateProgress();
            
            // 重置所有状态
            const statusElements = document.querySelectorAll('.status-badge');
            statusElements.forEach(element => {
                element.className = 'status-badge status-unknown';
                element.textContent = '未知';
            });
            
            // 清空测试结果
            document.getElementById('session-test-result').textContent = '等待测试...';
            document.getElementById('input-source-result').textContent = '等待测试...';
            document.getElementById('reference-space-result').textContent = '等待测试...';
            
            log('所有结果已清空', 'info');
        }

        // 页面加载完成后初始化
        window.addEventListener('load', () => {
            log('WebXR权限测试页面加载完成', 'info');
            refreshDeviceInfo();
        });
    </script>
</body>
</html>